<?php


namespace App\Kuafu\Shop\Controller\Applet;

use App\Kuafu\Activity\Enum\ActivityEnum;
use App\Kuafu\Activity\Service\ActivityImageMappingService;
use App\Kuafu\Activity\Service\ActivityService;
use App\Kuafu\Banner\Enum\BannerEnum;
use App\Kuafu\Banner\Service\BannerCommonService;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Common\Exceptions\CommonException;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Config\Service\ConfigService;
use App\Kuafu\Customer\Enum\CustomerCodeEnum;
use App\Kuafu\Customer\Enum\PlatformCodeEnum;
use App\Kuafu\Customer\Exceptions\CustomerException;
use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\Shop\Enum\ShopCacheEnum;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\DouyinSelfLibrary\DouyinSelfService;
use App\Kuafu\Shop\Service\ShopArchivesService;
use App\Kuafu\Shop\Service\ShopDistributionService;
use App\Kuafu\Shop\Service\ShopService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ShopController extends BaseController
{
    /**
     * 获取店铺详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShopInfoByShopId(Request $request)
    {
        $distributionId = (int)$request->get('distributionId');
        $shopId         = $request->shopId;

        // 这外层不用加缓存了，php层不会耗多少资源的
        $info = ShopService::getShopInfo($shopId);
        if (!$info) {
            throw new ShopException(ShopCodeEnum::ERR_SHOP_ID_NO_EXIST);
        }

        $distance = '';
        if ($request->lat && $request->lng) {
            if (
                !is_numeric($request->lat) ||
                !is_numeric($request->lng)
            ) {
                throw new ShopException(ShopCodeEnum::ERR_SHOP_INPUT);
            }

            $distance = CommonService::getDistance($request->lat, $request->lng, $info->lat, $info->lng);
        }

        $time         = ShopService::getShopBusinessTimeChangeByDb($info['startAt'], $info['endAt']);
        $shopStatus   = ShopService::getShopOpenStatus($info);
        $activityType = ActivityEnum::TYPE_REGISTRATION;
        $activityId   = ActivityService::getActivityIdByShopInfo($activityType, $shopId);
        $returnData   = [
            'id'                   => $info['id'],
            'shopMobile'           => $info['shopMobile'],
            'name'                 => $info['name'],
            'shortName'            => ShopService::getShortName($info->toArray()),// 门店简称
            'lng'                  => $info['lng'],
            'lat'                  => $info['lat'],
            'privateDrainageImg'   => $info->privateDrainageImg ? CommonService::joinImageUrl($info->privateDrainageImg) : '',
            'orderingQrCode'       => $info->orderingQrCode ? CommonService::joinImageUrl($info->orderingQrCode) : '',
            'status'               => $info->status,
            'openStatus'           => $shopStatus['openStatus'],
            'appletStatus'         => $info->appletStatus,
            'startAt'              => $time['startAt'],
            'endAt'                => $time['endAt'],
            'type'                 => $info['type'],
            'distance'             => (string)$distance,
            'address'              => $info['address'] ?? "",
            'dyCouponVerifySwitch' => $info['dyCouponVerifySwitch'],
            'introducer'           => $info['introducer'],
            'introducerText'       => Shop::INTRODUCER_TEXT[$info['introducer']] ?? new \stdClass()
        ];
        $lists        = ActivityImageMappingService::getImageListById($activityId)->toArray();
        $lists1       = $lists;
        foreach ($lists as &$value) {
            $value = CommonService::joinImageUrl($value['imageUrl']);
        }
        $str      = 'image';
        $listsArr = [];
        foreach ($lists1 as $key => $v) {
            $listsArr[$str . ($key + 1)] = CommonService::joinImageUrl($v['imageUrl']);
        }
        $activityList               = [
            'newUser' => [ // 新用户活动
                /**
                 * [
                 *  'image1' => '/a/b/c.jpg',
                 *  'image2' => '/a/b/c.jpg'
                 * ]
                 */
                'imageList1' => $lists,
                'imageList'  => $listsArr,
                'isShow'     => $activityId,
            ]
        ];
        $returnData['activityList'] = $activityList;

        // 显示门店的自配送信息
        $shopArchives                       = ShopArchivesService::getArchivesInfo($request->shopId);
        $returnData['minSelfDeliveryPrice'] = $shopArchives['minSelfDeliveryPrice'];
        $returnData['selfDeliveryNotice']   = $shopArchives['selfDeliveryNotice'];
        $returnData['isOpenSelfDelivery']   = $shopArchives['isOpenSelfDelivery'];

        $returnData['archives'] = [
            'manageEWechatPic' => $shopArchives['manageEWechatPic'],
            'manageEWechatUrl' => $shopArchives['manageEWechatUrl'],
            'eWechatPic'       => $shopArchives['eWechatPic'],
            'eWechatUrl'       => $shopArchives['eWechatUrl']
        ];

        // 是否传了分销渠道 Id
        $returnData['distributionInfo'] = null;
        if ($distributionId) {
            // 获取渠道相关信息
            $returnData['distributionInfo'] = ShopDistributionService::getEffectInfoById($distributionId);
            $returnData['appletStatus']     = 0;
        }

        // todo 获取门店满赠活动信息
        $giftActivity = ActivityService::getShopGiftActivityDetail(
            $info, ActivityEnum::CHANNEL_APPLET
        );
        if ($giftActivity) {
            $returnData['activityList']["giftActivity"] = array_merge([
                "detail"  => $giftActivity,
                "hasJoin" => $request->header('APPLET-TOKEN') &&
                    $giftActivity["limitJoinNum"]
                    && ActivityService::isJoinShopGiftActivity(
                        $shopId,
                        CustomerPlatformService::getUserId($request),
                        $giftActivity["id"],
                        $giftActivity
                    )
            ]);
        }

        return $this->success($returnData);
    }

    /**
     * 判断门店是否能正常点单
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getShopOrderStatus(Request $request): JsonResponse
    {
        $shopId  = (string)$request->get('shopId', '');
        $skuId   = (string)$request->get('skuId', '');
        $poiId   = (string)$request->get('poiId', '');
        $orderId = (string)$request->get('orderId', '');

        return $this->success((new ShopService(0, $shopId))->getShopOrderStatus($skuId, $poiId, $orderId));
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ShopException
     */
    public function getRecentlyShop(Request $request): JsonResponse
    {
        $lat = $request->get('lat', '');
        $lng = $request->get('lng', '');

        if (!is_numeric($lat) || !is_numeric($lng) || $lat >= 91 || $lng >= 181) {
            throw new ShopException(ShopCodeEnum::ERR_SHOP_INPUT);
        }

        return $this->success(ShopService::getRecentlyShop($lng, $lat));
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ShopException
     */
    public function getNearShop(Request $request): JsonResponse
    {
        $lat        = $request->get('lat', '');
        $lng        = $request->get('lng', '');
        $poiId      = (string)$request->get('poiId', '');
        $orderId    = (string)$request->get('orderId', '');
        $skuId      = (string)$request->get('skuId', '');
        $platformId = (int)$request->header('platformId', 1);
        $searchKey  = (string)$request->get('searchKey', '');// 支持门店名称+地址搜索(匹配门店名称和地址)

        if($platformId == PlatformCodeEnum::PLATFORM_APPLET_WECHAT_APPLET){
            $token = $request->header('APPLET-TOKEN');
            if (!$token) {
                throw new CommonException(CommonCodeEnum::ERR_NO_TOKEN);
            }
        }

        if (!is_numeric($lat) || !is_numeric($lng) || $lat >= 91 || $lng >= 181) {
            throw new ShopException(ShopCodeEnum::ERR_SHOP_INPUT);
        }
        if ($platformId == PlatformCodeEnum::PLATFORM_APPLET_DOUYIN) {
            $shopList = ShopService::getNearShopFromDy($lng, $lat, $platformId, $orderId, $poiId, $skuId);
        } else {
            $shopList = ShopService::getNearShop($lng, $lat, 10, $searchKey);
        }
        return $this->success($shopList);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function getUsuallyShop(Request $request): JsonResponse
    {
        return $this->success(ShopService::getUsuallyShop($request));
    }

    /**
     * 点餐页面弹窗整合
     * @param Request $request
     * @return JsonResponse
     * @throws CustomerException
     */
    public function popList(Request $request): JsonResponse
    {
        $userId = CustomerPlatformService::getUserId($request) ?: 0;
        $shopId = $request->header('shopId', 0);
        //获取券包
        $couponPackageId = $request->get('couponPackageId', 0);
        if (!$shopId) {
            throw new CustomerException(CustomerCodeEnum::ERR_CUSTOMER_PARAM_VALID);
        }
        $couponPackage = CustomerPlatformService::couponPackageInfo($shopId, $userId, $couponPackageId, true);
        //获取活动
        $activityType = ActivityEnum::TYPE_REGISTRATION;
        $activityId   = ActivityService::getActivityIdByShopInfo($activityType, $shopId);
        $lists        = ActivityImageMappingService::getImageListById($activityId)->toArray();
        foreach ($lists as &$value) {
            $value = CommonService::joinImageUrl($value['imageUrl']);
        }
        $activityList = [
            'newUser' => [ // 新用户活动
                /**
                 * [
                 *  'image1' => '/a/b/c.jpg',
                 *  'image2' => '/a/b/c.jpg'
                 * ]
                 */
                'imageList' => $lists,
                'isShow'    => $activityId,
            ]
        ];
        //获取弹窗
        $type     = BannerEnum::TYPE_POP;
        $field    = ['img'];
        $shopId   = $this->shopId;
        $shopInfo = ShopService::getShopInfo($shopId);
        $popImg   = BannerCommonService::getAppletPopImage($type, $shopId, $shopInfo['type'], $field, 'first');
        return $this->success(
            [
                'couponPackage' => $couponPackage,
                'activityList'  => $activityList,
                'popList'       => ['img' => $popImg]
            ]);
    }
}
